package com.gmt.realm;

import com.gmt.pojo.User;
import com.gmt.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author John.zhang
 * @version Id: AuthcRealm, v 1.0 2020/11/12 16:42 ZhiYong Exp $
 */
public class AuthcRealm extends AuthorizingRealm {

    @Resource
    private IUserService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println("授权的账号是：" + user.getUsername());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("roleA");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        System.out.println("开始认证：" + userName);
        User user = new User();
        user.setUsername(userName);
        // 根据账号认证
        List<User> list = service.query(user);
        if (list == null || list.size() != 1) {
            return null;
        }
        user = list.get(0);
        return new SimpleAuthenticationInfo(user
                , user.getPassword()
                , new SimpleByteSource("md5")
                , "authcRealm"
        );
    }
}
